package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * 该表现层用于文件上传
 */
@RestController
@RequestMapping("/admin/common")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取扩展名.jpg
        String extName = null;
        if (originalFilename != null) {
            extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        //定义文件扩展名
        String fileName= UUID.randomUUID()+ extName;
        //上传到OSS
        try {
            String path = aliOssUtil.upload(file.getBytes(), fileName);
            // 3返回成功
            return Result.success(path);
        } catch (IOException e) {
            //throw new RuntimeException(e);
            log.error("上传到OSS失败:{}",e.getMessage());
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
}
